<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\ActivityModel;
use app\common\model\ActivitySignModel;
use think\Db;
use think\Exception;

/**
 * 活动接口
 */
class Activity extends Api
{


    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['lists', 'detail', 'sign_list'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];


    /**
     * 发布活动
     */
    public function publish()
    {
        $param = $this->request->param();

        $rule = [
            'title' => 'require|max:200',
            'begin_time' => 'require|dateFormat:Y-m-d H:i:s',
            'fee' => 'require|number',
            'route_id' => 'require|number',
            'intro' => 'require|length:1,500',
        ];
        $msg = [];
        $check_res = $this->validate($param, $rule, $msg);
        if ($check_res !== true) {
            $this->error($check_res);
        }
        $user = $this->auth->getUser();

        $data = [
            'user_id' => $user['id'] ?? 0,
            'title' => $param['title'],
            'begin_time' => $param['begin_time'],
            'fee' => $param['fee'],
            'intro' => $param['intro'],
            'route_thumb' => $param['route_thumb'],
            'thumb' => $param['thumb'],
        ];
        $line = $this->getRouteLine();
        $data = array_merge($data, $line[$param['route_id']]);
        $create = ActivityModel::create($data);

        if ($create->id) {
            $this->success(__('活动发布成功'));
        } else {
            $this->error(__('活动发布失败'));
        }

    }


    /**
     * 发布活动
     */
    public function edit()
    {
        $param = $this->request->param();

        $rule = [
            'id' => 'require|number',
            'title' => 'require|max:200',
            'begin_time' => 'require|dateFormat:Y-m-d H:i:s',
            'fee' => 'require|number',
            'route_id' => 'require|number',
            'intro' => 'require|length:1,500',
        ];
        $msg = [];
        $check_res = $this->validate($param, $rule, $msg);
        if ($check_res !== true) {
            $this->error($check_res);
        }
        $user = $this->auth->getUser();
        $detail = ActivityModel::where('id', $param['id'])
            ->where('user_id', $user['id'])
            ->find();

        if (empty($detail)) {
            $this->error(__('id error'));
        }

        $data = [
            'user_id' => $user['id'] ?? 0,
            'title' => $param['title'],
            'begin_time' => $param['begin_time'],
            'fee' => $param['fee'],
            'intro' => $param['intro'],
        ];

        if (!empty($param['route_thumb'])) {
            $data['route_thumb'] = $param['route_thumb'];
        }

        if (!empty($param['thumb'])) {
            $data['thumb']  = $param['thumb'];
        }
        $line = $this->getRouteLine();
        $data = array_merge($data, $line[$param['route_id']]);

        if ($detail->save($data)) {
            $this->success(__('活动编辑成功'));
        } else {
            $this->error(__('活动编辑失败'));
        }

    }

    public function getRouteLine()
    {
        return [
            1 => [
                'route_id' => 1,
                'address' => '河南郑州CBD',
                'departure' => '郑州东站',
                'destination' => '森林公园',
            ],
            2 => [
                'route_id' => 2,
                'address' => '河南郑州CBD',
                'departure' => '森林公园',
                'destination' => '二七广场',
            ],
        ];
    }
    //线路
    public function route_line()
    {
        $this->success(__('成功'),  array_values($this->getRouteLine()));
    }
    //活动列表
    public function lists()
    {
        //0所有活动 1我发布的活动 2参与的活动 3热门活动
        $type = $this->request->param('type/d', 0);
        $page_size = $this->request->param('page_size/d', 15);
        if ($page_size < 1) {
            $this->error(__('Invalid parameters'));
        }

        $user_id = $this->auth->id ?? 0;

        $model = ActivityModel::field('id,title,begin_time,thumb,join_num');
        //排序处理
        if ($type == 3) {
            $model->order('join_num', 'desc');
        } else {
            $model->order('id', 'desc');
        }
        //活动类型处理
        if ($type == 1) {
            $model->where('user_id', $user_id);
        } elseif ($type == 2) {
            $ids = [];
            if ($user_id) {
                $ids = ActivitySignModel::where('user_id', $user_id)->column('activity_id');
            }
            $model->whereIn('id', $ids);
        }

        $list = $model->paginate($page_size);
        if ($list->total()) {
            $list->each(function ($item) use ($user_id) {
                $item->data('login_user_id', $user_id);
                $item->append(['status_text']);
                return $item;
            });
        }
        $this->success(__('成功'), $list);
    }


    //活动详情
    public function detail()
    {
        $id = $this->request->param('id/d', 0);
        if ($id < 1) {
            $this->error(__('id error'));
        }

        ActivityModel::where('id', $id)->setInc('view');
        $info = (new ActivityModel())->field('deletetime', true)
            ->where('id', $id)
            ->find();
        if ($info) {
            $user_id = $this->auth->id ?? 0;
            $info->data('login_user_id', $user_id);
            $info->append(['status_text']);
        }
        $this->success(__('成功'), (object)$info);
    }

    //报名
    public function sign()
    {
        $id = $this->request->param('id/d', 0);
        if ($id < 1) {
            $this->error(__('id error'));
        }
        $user_id = $this->auth->id ?? 0;
        $count = ActivitySignModel::where([
            'user_id' => $user_id,
            'activity_id' => $id
        ])->count();
        if ($count) {
            $this->error(__('你已经报过名了'));
        }

        Db::startTrans();
        try {

            ActivitySignModel::create([
                'user_id' => $user_id,
                'activity_id' => $id
            ]);
            ActivityModel::where('id', $id)->setInc('join_num');
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error(__('Operation failed'));
        }

        $this->success(__('Operation completed'));
    }


    //取消报名
    public function cancel_sign()
    {
        $id = $this->request->param('id/d', 0);
        if ($id < 1) {
            $this->error(__('id error'));
        }
        $user_id = $this->auth->id ?? 0;
        $sign_id = ActivitySignModel::where([
            'user_id' => $user_id,
            'activity_id' => $id
        ])->value('id');
        if (!$sign_id) {
            $this->error(__('未报名'));
        }

        Db::startTrans();
        try {
            ActivitySignModel::where('id', $sign_id)->delete();
            ActivityModel::where('id', $id)->setDec('join_num');
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error(__('Operation failed'));
        }

        $this->success(__('Operation completed'));
    }

    //报名列表
    public function sign_list()
    {
        $id = $this->request->param('id/d', 0);
        if ($id < 1) {
            $this->error(__('id error'));
        }
        $page_size = $this->request->param('page_size/d', 15);
        if ($page_size < 1) {
            $this->error(__('Invalid parameters'));
        }

        $user_ids = ActivitySignModel::where('activity_id', $id)->column('user_id');
        $model = \app\common\model\User::field('id,name,nickname,mobile,avatar,createtime');
        $model->whereIn('id', $user_ids);

        $list = $model->paginate($page_size);
        if ($list->total()) {
            $list->each(function ($item) {
                $item->append([], true);
                if ($item->mobile) {
                    $item->mobile = substr($item->mobile, 0, 3) . '****' . substr($item->mobile, -4);
                }
                $item->name = (string)($item->name ?: $item->nickname);
                unset($item->nickname);
                return $item;
            });
        }
        $this->success(__('成功'), $list);
    }

}
